<template>
  <div id="app">
    <el-card style="margin: 20px 0">
      <!-- 三级联动 -->
      <level3 @getId="getId" :addAttr="addAttr"></level3>
    </el-card>
    <el-card>
      <div class="table" v-show="!addAttr">
        <!-- :disabled="!id.item3Id" 当三级联动的第三个id有的时候可以添加属性 -->
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrs"
          :disabled="!id.item3Id"
          >添加属性</el-button
        >
        <!-- table表格 -->
        <el-table border :data="info">
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="150"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                type="success"
                v-for="item in row.attrValueList"
                :key="item.id"
                style="margin: 0 20px"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="{ row }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="update(row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加属性 / 修改属性-->
      <div class="addAttr" v-show="addAttr">
        <!-- 添加属性的属性名 -->
        <el-form inline :data="AttrinfoList">
          <el-form-item label="属性名" width="180">
            <el-input
              placeholder="请输入属性名"
              v-model="AttrinfoList.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- 添加属性值的按钮 -->
        <div class="addBtn">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addAttrsList"
            :disabled="!AttrinfoList.attrName"
            >添加属性值</el-button
          >
          <el-button type="">取消</el-button>
        </div>
        <!-- 属性值得列表 -->
        <div class="attrList">
          <el-table :data="AttrinfoList.attrValueList">
            <el-table-column
              label="序号"
              align="center"
              type="index"
            ></el-table-column>
            <el-table-column label="属性值名称">
              <template slot-scope="{ row, $index }">
                <el-input
                  type="text"
                  v-model="row.valueName"
                  v-show="row.flag"
                  @blur="toLook(row)"
                  :ref="$index"
                />
                <span v-show="!row.flag" @click="toFocus(row, $index)">
                  {{ row.valueName }}
                </span>
              </template>
            </el-table-column>
            <!-- 删除属性值 -->
            <el-table-column label="操作">
              <template slot-scope="{ row, $index }">
                <el-popconfirm
                  :title="`确定删除 ${row.valueName} 吗？`"
                  @onConfirm="delvalueName($index)"
                >
                  <el-button
                    slot="reference"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                  ></el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 保存和取消 -->
        <div>
          <el-button
            type="primary"
            :disabled="AttrinfoList.attrValueList < 1"
            @click="save"
            >保存</el-button
          >
          <el-button type="" @click="addAttr = false">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getattrInfoList, saveAttrInfo } from "@/api/product/attr";
// 深拷贝插件
import cloneDeep from "lodash/cloneDeep";
import level3 from "@/components/Level/level3.vue";
export default {
  name: "Attr",
  components: { level3 },
  data() {
    return {
      id: {},
      info: [],
      addAttr: false, //是否显示添加属性
      //   存放添加或修改的属性名和属性值
      AttrinfoList: {
        attrName: "", //属性名
        attrValueList: [],
        categoryId: 0, // 三级联动的id
        categoryLevel: 3,
      },
    };
  },
  methods: {
    async getId(id) {
      console.log(id);
      this.id = { ...id };
      //   把三级ID给到添加属性上;
      //   this.AttrinfoList.categoryId = id.item3Id;
      this.getList();
    },
    async getList() {
      let res = await getattrInfoList(this.id);
      console.log(res);
      if (res.code == 200) {
        this.info = res.data;
      }
    },
    // 添加属性值
    addAttrsList() {
      console.log(this.AttrinfoList.attrValueList);
      this.AttrinfoList.attrValueList.push({
        //   attrId 是相应的属性id 我们是添加属性所以没有相应的id，目前是带undefined给服务器
        attrId: this.AttrinfoList.id, // 属性名的id
        valueName: "", // 属性值的名称
        flag: true, //用来替换输入框和span
      });
      // 我们要让输入框聚焦 我们可以让数组的最后一位进行聚焦 给input添加
      // 一个ref 然后通过refs.数组的最后一个来添加
      // 为什么要用 nextTick能 因为我们在添加的时候vue是异步的 dom还没有获取到 用
      // nextTick就能获取到最新的DOM
      this.$nextTick(() => {
        console.log(this.$refs[this.AttrinfoList.attrValueList.length - 1]);
        this.$refs[this.AttrinfoList.attrValueList.length - 1].focus();
      });
    },
    // 添加属性
    addAttrs() {
      this.addAttr = true;
      //   清空之前输入的内容
      this.AttrinfoList = {
        attrName: "", //属性名
        attrValueList: [],
        categoryId: this.id.item3Id, // 三级联动的id
        categoryLevel: 3,
      };
    },
    // 修改属性
    update(row) {
      // 修改的时候给row添加上flag去判断他是显示span还是input
      row.attrValueList.forEach((element) => {
        // console.log(element);
        element.flag = false;
      });
      console.log(row);
      this.addAttr = true;
      // 进行一个深拷贝 我们借用插件来实现
      this.AttrinfoList = cloneDeep(row);
    },
    // 当输入框输入完成之后切换成span标签
    toLook(row) {
      // 如果是空格不符合
      if (row.valueName.trim() === "") {
        this.$message.error("请输入正常的属性名");
        return;
      }
      console.log(this.AttrinfoList.attrValueList);

      let res = this.AttrinfoList.attrValueList.some((item) => {
        // 这个判断就是要把自身抛出去
        if (row !== item) {
          console.log(item);
          return item.valueName === row.valueName;
        }
      });
      if (res) {
        this.$message.error("上面已经声明这个属性了o");
        return;
      }
      row.flag = false;
    },
    // 当点击span的时候让他自动聚焦
    toFocus(row, index) {
      row.flag = true;
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },

    // 删除属性值
    delvalueName(index) {
      this.AttrinfoList.attrValueList.splice(index, 1);
    },
    // 保存属性
    async save() {
      // 保存的时候我们要把添加的空值和自己定义的值flag删除
      this.AttrinfoList.attrValueList = this.AttrinfoList.attrValueList.filter(
        (item) => {
          if (item.valueName !== "") {
            delete item.flag;
            return true;
          }
        }
      );
      // console.log(this.AttrinfoList);
      let res = await saveAttrInfo(this.AttrinfoList);
      console.log(res);
      if (res.code === 200) {
        this.$message.success("保存成功");
        this.addAttr = false;
        this.getList();
      } else {
        this.$message.error("保存失败");
      }
    },
  },
};
</script>
